import { dataUrlToBlob, filePicker, fileToDataUrl } from '../file';

export const downloadImage = (url: string, args = { useCache: false }, callback: any) => {
  const { useCache } = args;
  const image = new Image();
  image.setAttribute('crossOrigin', 'anonymous');
  let src: string;
  if (useCache || url.indexOf('data:') === 0) {
    src = url;
  } else {
    const time = new Date().getTime();
    src = `${url}${url.indexOf('?') === -1 ? '?' : '&'}${time}=${time}`;
  }
  image.src = src;
  let callbackFlag = false;
  let success = false;
  const _callback = () => {
    if (!callbackFlag && callback) {
      callback(image, success);
    }
    callbackFlag = true;
  };
  image.onload = () => {
    success = true;
    _callback();
  };
  image.onerror = _callback;
  image.onabort = _callback;
};

export const imageToDataUrl = (
  image: any,
  args: {
    maxWidth: number;
    maxHeight: number;
    type?: string;
    quality?: number;
  },
) => {
  const { maxWidth, maxHeight, type = 'image/png', quality = 1 } = args;
  const originWidth = image.width;
  const originHeight = image.height;
  let targetWidth = originWidth;
  let targetHeight = originHeight;
  if (originWidth > maxWidth || originHeight > maxHeight) {
    if (originWidth / originHeight > maxWidth / maxHeight) {
      targetWidth = maxWidth;
      targetHeight = Math.round(maxWidth * (originHeight / originWidth));
    } else {
      targetHeight = maxHeight;
      targetWidth = Math.round(maxHeight * (originWidth / originHeight));
    }
  }
  const canvas = document.createElement('canvas');
  canvas.width = targetWidth;
  canvas.height = targetHeight;
  const context: any = canvas.getContext('2d');
  context.clearRect(0, 0, targetWidth, targetHeight);
  context.drawImage(image, 0, 0, targetWidth, targetHeight);
  return canvas.toDataURL(type, quality);
};

export const urlToDataUrl = (
  url: string,
  args: {
    maxWidth: number;
    maxHeight: number;
    type?: string;
    quality?: number;
    useCache: boolean;
  },
  callback: any,
) => {
  downloadImage(url, args, (image: any) => {
    if (callback) {
      callback(imageToDataUrl(image, args));
    }
  });
};

/**
 * 图片选择
 *
 * @param {function} complete 回调事件
 */
export const imagePicker = (
  callback: any,
  option?: {
    accept?: string;
    capture?: string;
    multiple?: string;
    compress?: {
      maxWidth: number;
      maxHeight: number;
      type: string;
      quality: number;
    };
  },
) => {
  const { compress, ...otherOption } = option || {};
  filePicker(
    compress
      ? (fileObjs: any) => {
          const results: any = [];
          for (let i = 0, { length } = fileObjs; i < length; i += 1) {
            const fileObj = fileObjs[i];
            fileToDataUrl(fileObj.file, (dataUrl: string) => {
              downloadImage(dataUrl, { useCache: true }, (image: any) => {
                const compressDataUrl = imageToDataUrl(image, compress);
                const compressBlob = dataUrlToBlob(compressDataUrl);
                let filename = fileObj.file.name || '';
                const index = filename.lastIndexOf('.');
                if (index !== -1) {
                  filename = filename.substring(0, index);
                }
                filename = `${filename}${compress.type ? compress.type.replace('image/', '.') : '.png'}`;
                // @ts-ignore
                compressBlob.name = filename;
                results[i] = {
                  file: compressBlob,
                  originFile: fileObj.file,
                  filename,

                  dataUrl: compressDataUrl,
                  originDataUrl: dataUrl,
                };
                if (results.filter((item: any) => !!item).length === length) {
                  callback(results);
                }
              });
            });
          }
        }
      : callback,
    { ...otherOption, accept: 'image/*' },
  );
};
